package com.pan.crawler.auto;

import com.pan.crawler.Page;
import com.pan.crawler.auto.action.TurnPage;
import com.pan.download5.parse.entity.auto.impl.AutoPage;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;

import java.time.Duration;

public class AutoCrawlerPage implements Page {
    private EdgeDriver edgeDriver;

    {
        this.edgeDriver = new EdgeDriver();
        EdgeOptions edgeOptions = new EdgeOptions();
        edgeOptions.addArguments("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
    }


    private String xpath;
    private String clearRegex;
    private TurnPage turnPage;


    public AutoCrawlerPage(AutoPage autoPage) {
        this.xpath = autoPage.getXpath();
        this.clearRegex = autoPage.getClearRegex();
        this.turnPage = new TurnPage(autoPage.getNext());
    }




    @Override
    public String get(Chapter chapter) {
        String url = chapter.getUrl();
        edgeDriver.navigate().to(url);
        StringBuffer content = new StringBuffer();
        for (;;) {
            WebElement contentElement = edgeDriver.findElement(By.xpath(xpath));
            String text = contentElement.getText();
            content.append( text.replaceAll(clearRegex,"") );
            if (!turnPage.execute(edgeDriver)){
                break;
            }
        }
        return content.toString();
    }

    @Override
    public void close() {
        edgeDriver.quit();
    }
}
